package com.test.services;

import java.util.ArrayList;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ParseException;
import android.util.Log;

import com.test.models.StudentModel;

public class StudentUserService {

	private static final String TAG = "StudentUserService";
	public StudentModel studentModelObj = new StudentModel();
	private JSONArray jArray;
	private String result;

	public StudentModel RetrieveUser(String username, String password) {

		final String un = username;
		final String pw = password;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("username", un));
		Log.d(TAG, "Post Parameter Username " + un);
		postParameters.add(new BasicNameValuePair("password", pw));
		Log.d(TAG, "Post Parameter password " + pw);

		String response = null;
		try {
			response = HttpClientService.executeHttpPost(
					"http://blackvault.net63.net/testscript.php",
					postParameters);

			Log.d(TAG, "response " + response);
			result = response.toString();
			result = result.replaceAll("\\s+", " ");

			try {
				jArray = new JSONArray(result);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					studentModelObj.studentNumber = json_data
							.getInt("usersname");
					studentModelObj.firstName = json_data
							.getString("firstname");
					studentModelObj.surname = json_data.getString("surname");
					studentModelObj.studentPassword = json_data
							.getString("password");
					studentModelObj.email = json_data.getString("email");
			

				}
			} catch (JSONException e1) {
				Log.e(TAG, "JSONException " + e1.toString());

			} catch (ParseException e1) {
				Log.e(TAG, "ParseException " + e1.toString());
			}

		} catch (HttpException ex) {
			Log.e(TAG, "HTTP error " + ex.toString());
		} catch (Exception e) {

			Log.e(TAG, "Response Error " + e.toString());
		}

		Log.d(TAG, "Returning res " + result);
		return studentModelObj;
	}

}
